﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Shell;
using SABnzbdNET.Dialogs;
using SABnzbdNET.Model;
using SABnzbdNET.ServiceAgents;

namespace SABnzbdNET.Views
{
    /// <summary>
    /// Interaction logic for ServerStatus.xaml
    /// </summary>
    public partial class ServerStatus : UserControl
    {
        readonly System.Windows.Threading.DispatcherTimer timer = new System.Windows.Threading.DispatcherTimer();

        private static string ServerUrl
        {
            get
            { 
                string temp = Properties.Settings.Default.ServerPath + Properties.Settings.Default.ServerPathMode_Status + Properties.Settings.Default.ServerPathParameters;
                return string.Format(temp, Properties.Settings.Default.ServerUsername, Properties.Settings.Default.ServerPassword, Properties.Settings.Default.ServerAPIKey);
            }
        }

        public ServerStatus()
        {
            InitializeComponent();
        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            timer.Tick += TimerTick;
            timer.Start();
            Update();
        }

        void TimerTick(object sender, EventArgs e)
        {
            GetInfo();
        }

        private void hlnServer_RequestNavigate(object sender, System.Windows.Navigation.RequestNavigateEventArgs e)
        {
            string navigateUri = hlnServer.NavigateUri.ToString();
            // if the URI somehow came from an untrusted source, make sure to
            // validate it before calling Process.Start(), e.g. check to see
            // the scheme is HTTP, etc.
            Process.Start(new ProcessStartInfo(navigateUri));
            e.Handled = true;
        }

        public void Update()
        {
            timer.Interval = new TimeSpan(0, Properties.Settings.Default.TimerInterval, 0);
            timer.IsEnabled = true;
            GetInfo();
        }

        private void GetInfo()
        {
            Mouse.OverrideCursor = Cursors.AppStarting;
            SetStatusMessage("Updating", "Updating");
            new ServerAgent().GetInfo(DeployResult);
        }

        private void DeployResult(ServerInfo info, string errorMessage)
        {
            ((App)Application.Current).CurrentServerInfo = info;
            if (info == null)
            {
                SetStatusMessage("Error updating: " + errorMessage, "Error updating");
                return;
            }

            lblStatusValue.Content = info.Status;
            var firstJob = info.Jobs.FirstOrDefault();
            if (firstJob != null)
            {
                lblTitleValue.Content = firstJob.Title;
                lblSpeedValue.Content = info.KbPerSec.ToString("N2") + " kb/s";
                progressBar.Value = (int)firstJob.Progress;
                progressBar.ToolTip = (int)firstJob.Progress + "%";
                Application.Current.MainWindow.TaskbarItemInfo = new TaskbarItemInfo
                {
                    ProgressValue = ((double)firstJob.Progress/100),
                    ProgressState = info.Paused ? TaskbarItemProgressState.Paused : TaskbarItemProgressState.Normal
                };
            }
            else
            {
                lblTitleValue.Content = "N/A";
                lblSpeedValue.Content = "N/A";
                progressBar.Value = 0;
                progressBar.ToolTip = "0%";
            }

            listViewQueue.Items.Clear();
            foreach (var job in info.Jobs)
            {
                listViewQueue.Items.Add(job);
            }
            if (Application.Current.MainWindow is Main)
            {
                SetStatusMessage("Last updated " + DateTime.Now,
                    string.Format("Status: {0}{1}Title: {2}{3}Speed: {4}{5}Progress: {6}"
                    , lblStatusValue.Content, Environment.NewLine, lblTitleValue.Content, Environment.NewLine
                    , lblSpeedValue.Content, Environment.NewLine, progressBar.ToolTip));
            }
            Mouse.OverrideCursor = null;
        }

        private void SetStatusMessage(string statusMessage, string notifyIconTooltip)
        {
            if (Application.Current.MainWindow is Main)
            {
                ((Main)Application.Current.MainWindow).StatusMessage = statusMessage;
                ((Main)Application.Current.MainWindow).NotifyIconTooltip = notifyIconTooltip;
            }
        }
    }
}
